/**
 * 
 */
package org.dse.html.processor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dse.html.TagName;
import org.dse.html.TagResultContainer;

/**
 * This class is used to process the heading content.
 * 
 * It is configged in the application context and added into the
 * TagProcessorContainer singleton.
 * 
 * @author zhangchen
 * 
 */
public class HeadingTagProcessor implements TagProcessor {

	private static final String[] regStr = new String[] { "<h1[^>]*?>(.*?)</h1>",
			"<h2[^>]*?>(.*?)</h2>", "<h3[^>]*?>(.*?)</h3>", "<h4[^>]*?>(.*?)</h4>",
			"<h5[^>]*?>(.*?)</h5>", "<h6[^>]*?>(.*?)</h6>" };

	private static Pattern[] ptn = new Pattern[regStr.length];

	static {
		for (int i = 0; i < regStr.length; i++) {
			ptn[i] = Pattern.compile(regStr[i], Pattern.CASE_INSENSITIVE
					| Pattern.UNICODE_CASE | Pattern.DOTALL);
		}
	}

	/**
	 * Process a heading tag.
	 * 
	 * @param htmlContent
	 *            the whole content of current processed html document
	 * @param index
	 *            the start index of the current tag
	 * @param container
	 *            the TagResultContainer which the processor sends results to
	 */
	public void processTag(String htmlContent, int index,
			TagResultContainer container) {
		char level = htmlContent.charAt(index + 2);
		int i_level = (int) level - 48;
		Pattern p = ptn[i_level - 1];

		Matcher matcher = p.matcher(htmlContent);
		if (matcher.find(index)) {
			String headingContent = matcher.group(1);
			// add to result container with tag name "hx"
			container.addResult(TagName.HEADING_TAG_NAME + level,
					headingContent);
		}
	}
}
